package com.itycu.server.core;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.ibatis.exceptions.TooManyResultsException;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.ParameterizedType;
import java.util.List;

/**
 * 基于通用MyBatis Mapper插件的Service接口的实现
 */
public abstract class AbstractService<T> implements Service<T> {

    @Autowired
    protected Mapper<T> mapper;

    private Class<T> modelClass;    // 当前泛型真实类型的Class

    public AbstractService() {
        ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
        modelClass = (Class<T>) pt.getActualTypeArguments()[0];
    }

    @Override
    public int save(T model) {
        return mapper.insert(model);
    }

    @Override
    public int save(List<T> models) {
        return mapper.insertBatchSomeColumn(models);
    }

    @Override
    public int deleteById(Long id) {
        return mapper.deleteById(id);
    }

    @Override
    public int deleteByIds(List<Long> ids) {
        return mapper.deleteBatchIds(ids);
    }

    @Override
    public int deleteBy(String fieldName, Object value) {
        QueryWrapper<T> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(fieldName, value);
        return mapper.delete(queryWrapper);
    }

    @Override
    public int update(T model) {
        return mapper.updateById(model);
    }

    @Override
    public T findById(Long id) {
        return mapper.selectById(id);
    }

    @Override
    public T findBy(String fieldName, Object value) throws TooManyResultsException {
        QueryWrapper<T> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(fieldName, value);
        return mapper.selectOne(queryWrapper);
    }

    @Override
    public List<T> findByIds(String ids) {
        return null;
    }

    @Override
    public List<T> findByIds(String ids, Boolean deleted) {
        return null;
    }

    @Override
    public List<T> findAll() {
        QueryWrapper<T> queryWrapper = new QueryWrapper<>();
        return mapper.selectList(queryWrapper);
    }

    @Override
    public Long selectCount(String fieldName, Object value) {
        QueryWrapper<T> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(fieldName, value);
        return mapper.selectCount(queryWrapper);
    }
}
